<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Container;
use think\response\Json;


/**
 * 接口用成功返回方法
 * @param null $data
 * @param string $msg
 * @return Json
 */
function success($data = null, string $msg = '成功')
{
	return json([
		'code' => 200,
		'msg' => $msg,
		'data' => $data
	]);
}

/**
 * 接口用错误返回方法
 * @param int $code
 * @param string|null $msg
 * @return Json
 */
function error(int $code, string $msg = null)
{
	$errorCode = [
		400 => '参数缺失/参数不正确',
		401 => '用户没有被认证',
		402 => '网络错误',
		403 => '验证码错误',
		404 => '访问的资源不存在',
		405 => '请求方法不被允许',
		406 => '用户token失效',
		407 => '账号已存在',
		408 => '账号或密码错误',
		409 => '今天已签到，请勿重复签到',
		429 => '访问次数过多',
		500 => '拒绝访问',
		501 => '验证码已过期',
		503 => '服务暂时下线，请稍后重试',
		508 => '非法的token',
		512 => '其他客户端登录了',
		514 => 'Token 过期了',
	];
	return json([
		'code' => $code,
		'msg' => $msg ?: $errorCode[$code],
		'data' => null
	]);
}

/**
 * 给手机发送验证码
 * @param $phone
 * @param $data
 * @param $tempId
 * @return array
 */
function sendPhoneCode($phone,$data,$tempId)
{
	$accountSid = '8a216da85afaadec015b0e9bee650650';   //主账号
	$accountToken = 'eb59ceb68d9848a6ad570aeddd4d2dbe';  //主账号token
	$appId = '8a216da8612cf2fe01614058027b03d7';        //应用id
	$serverIP='app.cloopen.com';   //请求地址，格式如下，不需要写https://
	$serverPort='8883';           //请求端口
	$softVersion='2013-12-26';     //REST版本号

	$rest = new PhoneCode\REST($serverIP,$serverPort,$softVersion);
	$rest->setAccount($accountSid,$accountToken);
	$rest->setAppId($appId);
	// 发送模板短信
	$result = $rest->sendTemplateSMS($phone,$data,$tempId);
	if($result == NULL ) {
		//echo "result error!";
		//break;
		return array('status'=> 203,'message'=>'result error!');
	}
	if($result->statusCode!=0) {
		return array('status'=>$result->statusCode,'message'=>$result->statusMsg);
		//TODO 添加错误处理逻辑
	}else{
		return array('status'=> 200,'message'=> $data[0]);
		//TODO 添加成功处理逻辑
	}

}
